package com.nearbymap.maps;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nearbymap.model.LatLng;
import com.nearbymap.model.PlacesResponse;
import com.nearbymap.model.XmlResponse;
import com.nearbymap.tooling.XmlService;

@Service
public class PlacesService {

	@Autowired
	private XmlService xmlService;
	private String placeTypeEnc;

	public PlacesService() {
		try {
			this.placeTypeEnc = URLEncoder.encode("cafe|bar|restaurant|park|bakery|bowling_alley|food|library|shopping_mall", "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public URL getPlacesUrl(LatLng location, int radiusMeters) {
		try {
			StringBuffer urlBuffer = 
					new StringBuffer("https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=").append(location)
							.append("&radius=").append(radiusMeters)
							.append("&types=").append(placeTypeEnc)
							.append("&sensor=false&key=AIzaSyBPVvCreobK1QOtOEZvqXvD1ed1qS2HNHM");
			System.out.println("PlacesUrl: " + urlBuffer.toString());
			return new URL(urlBuffer.toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public PlacesResponse getPlaces(LatLng location, int radiusMeters) {
		return new PlacesResponse(xmlService.query(getPlacesUrl(location, radiusMeters)));
	}

	public XmlResponse query(URL xmlServiceUrl) {
		return xmlService.query(xmlServiceUrl);
	}
}
